Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
intl-messageformat
Advanced tools
Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
The intl-messageformat package is a library for internationalization that allows formatting of messages including variable replacement, number and date formatting, and pluralization. It is built on the Internationalization API provided by modern browsers and can be used in both browser and Node.js environments.
Variable Replacement
This feature allows you to insert variables into your message strings.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('My name is {name}.');
const output = message.format({ name: 'Alice' });
console.log(output); // 'My name is Alice.'
Number Formatting
This feature allows you to format numbers according to the locale, including decimal and thousand separators.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('The price is {price, number}.', 'en-US');
const output = message.format({ price: 123456.78 });
console.log(output); // 'The price is 123,456.78.'
Date Formatting
This feature allows you to format dates according to the locale.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('Today is {today, date, long}.', 'en-US');
const output = message.format({ today: new Date() });
console.log(output); // 'Today is January 1, 2020.'
Pluralization
This feature allows you to handle plural forms of words based on numeric values.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('{numPhotos, plural, =0{no photos} =1{one photo} other{# photos}}', 'en-US');
const output = message.format({ numPhotos: 1000 });
console.log(output); // '1000 photos'
FormatJS is a set of JavaScript libraries that includes intl-messageformat and other internationalization capabilities like message extraction and locale data management. It provides a more comprehensive solution compared to intl-messageformat alone.
i18next is a full-featured internationalization framework for JavaScript. It offers a wide range of features including variable replacement, pluralization, and context handling. It is more feature-rich and has a larger ecosystem compared to intl-messageformat.
Messageformat is a library for ICU MessageFormat strings that supports plural and select messages, nested formats, and more. It is similar to intl-messageformat but also includes a compiler that can optimize message functions.
Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
This package aims to provide a way for you to manage and format your JavaScript app's string messages into localized strings for people using your app. You can use this package in the browser and on the server via Node.js.
This implementation is based on the Strawman proposal, but there are a few places this implementation diverges.
Note: This IntlMessageFormat
API may change to stay in sync with ECMA-402, but this package will follow semver.
Messages are provided into the constructor as a String
message, or a pre-parsed AST object.
var msg = new IntlMessageFormat(message, locales, [formats], [opts]);
The string message
is parsed, then stored internally in a compiled form that is optimized for the format()
method to produce the formatted string for displaying to the user.
var output = msg.format(values);
A very common example is formatting messages that have numbers with plural labels. With this package you can make sure that the string is properly formatted for a person's locale, e.g.:
var MESSAGES = {
'en-US': {
NUM_PHOTOS:
'You have {numPhotos, plural, ' +
'=0 {no photos.}' +
'=1 {one photo.}' +
'other {# photos.}}'
},
'es-MX': {
NUM_PHOTOS:
'Usted {numPhotos, plural, ' +
'=0 {no tiene fotos.}' +
'=1 {tiene una foto.}' +
'other {tiene # fotos.}}'
}
};
var output;
var enNumPhotos = new IntlMessageFormat(MESSAGES['en-US'].NUM_PHOTOS, 'en-US');
output = enNumPhotos.format({ numPhotos: 1000 });
console.log(output); // => "You have 1,000 photos."
var esNumPhotos = new IntlMessageFormat(MESSAGES['es-MX'].NUM_PHOTOS, 'es-MX');
output = esNumPhotos.format({ numPhotos: 1000 });
console.log(output); // => "Usted tiene 1,000 fotos."
The message syntax that this package uses is not proprietary, in fact it's a common standard message syntax that works across programming languages and one that professional translators are familiar with. This package uses the ICU Message syntax and works for all CLDR languages which have pluralization rules defined.
Uses industry standards: ICU Message syntax and CLDR locale data.
Supports plural, select, and selectordinal message arguments.
Formats numbers and dates/times in messages using Intl.NumberFormat
and Intl.DateTimeFormat
, respectively.
Optimized for repeated calls to an IntlMessageFormat
instance's format()
method.
Supports defining custom format styles/options.
Supports escape sequences for message syntax chars, e.g.: "\\{foo\\}"
will output: "{foo}"
in the formatted output instead of interpreting it as a foo
argument.
Intl
DependencyThis package assumes that the Intl
global object exists in the runtime. Intl
is present in all modern browsers (IE11+) and Node (with full ICU). The Intl
methods we rely on are:
Intl.NumberFormat
for number formatting (can be polyfilled using Intl.js)Intl.DateTimeFormat
for date time formatting (can be polyfilled using Intl.js)Intl.PluralRules
for plural/ordinal formatting (can be polyfilled using intl-pluralrules)<script src="intl-messageformat/intl-messageformat.min.js"></script>
Simply require()
this package:
var IntlMessageFormat = require('intl-messageformat');
NOTE: Your Node has to include full ICU
IntlMessageFormat
ConstructorTo create a message to format, use the IntlMessageFormat
constructor. The constructor takes three parameters:
message - {String | AST} - String message (or pre-parsed AST) that serves as formatting pattern.
locales - {String | String[]} - A string with a BCP 47 language tag, or an array of such strings. If you do not provide a locale, the default locale will be used. When an array of locales is provided, each item and its ancestor locales are checked and the first one with registered locale data is returned. See: Locale Resolution for more details.
[formats] - {Object} - Optional object with user defined options for format styles.
[opts] - { formatters?: Formatters }
: Optional options.
formatters
: Map containing memoized formatters for performance.var msg = new IntlMessageFormat('My name is {name}.', 'en-US');
IntlMessageFormat
uses Intl.NumberFormat.supportedLocalesOf()
to determine which locale data to use based on the locales
value passed to the constructor. The result of this resolution process can be determined by call the resolvedOptions()
prototype method.
resolvedOptions()
MethodThis method returns an object with the options values that were resolved during instance creation. It currently only contains a locale
property; here's an example:
var msg = new IntlMessageFormat('', 'en-us');
console.log(msg.resolvedOptions().locale); // => "en-US"
Notice how the specified locale was the all lower-case value: "en-us"
, but it was resolved and normalized to: "en-US"
.
format(values)
MethodOnce the message is created, formatting the message is done by calling the format()
method on the instance and passing a collection of values
:
var output = msg.format({ name: 'Eric' });
console.log(output); // => "My name is Eric."
Note: A value must be supplied for every argument in the message pattern the instance was constructed with.
getAst
MethodReturn the underlying AST for the compiled message
formatXMLMessage
methodFormats message containing XML tags & can be used to embed rich text formatters such as React. For example:
var mf = new IntlMessageFormat('hello <b>world</b>', 'en');
mf.formatXMLMessage({ b: str => <span>{str}</span> });
// returns ['hello ', React element rendered as <span>world</span>]
Define custom format styles is useful you need supply a set of options to the underlying formatter; e.g., outputting a number in USD:
var msg = new IntlMessageFormat('The price is: {price, number, USD}', 'en-US', {
number: {
USD: {
style: 'currency',
currency: 'USD'
}
}
});
var output = msg.format({ price: 100 });
console.log(output); // => "The price is: $100.00"
In this example, we're defining a USD
number format style which is passed to the underlying Intl.NumberFormat
instance as its options.
We also expose another entry point via intl-messageformat/core
that does not contain the parser from intl-messageformat-parser
. This is significantly smaller than the regular package but expects the message passed in to be in AST
form instead of string. E.g:
import IntlMessageFormat from 'intl-messageformat';
new IntlMessageFormat('hello').format(); // prints out hello
// is equivalent to
import IntlMessageFormat from 'intl-messageformat/core';
import parser from 'intl-messageformat-parser';
new IntlMessageFormat(parser.parse('hello')).format(); // prints out hello
This helps performance for cases like SSR or preload/precompilation-supported platforms since AST
can be cached.
For complex messages, initializing Intl.*
constructors can be expensive. Therefore, we allow user to pass in formatters
to provide memoized instances of these Intl
objects. This opts combines with passing in AST + using core entry point and intl-format-cache
can speed things up by 30x per the benchmark down below.
For example:
import IntlMessageFormat from 'intl-messageformat';
import memoizeIntlConstructor from 'intl-format-cache';
const formatters = {
getNumberFormat: memoizeIntlConstructor(Intl.NumberFormat),
getDateTimeFormat: memoizeIntlConstructor(Intl.DateTimeFormat),
getPluralRules: memoizeIntlConstructor(Intl.PluralRules)
};
new IntlMessageFormat('hello {number, number}', 'en', undefined, {
formatters
}).format({ number: 3 }); // prints out `hello, 3`
This example shows how to use the ICU Message syntax to define a message that has a plural label; e.g., "You have 10 photos"
:
You have {numPhotos, plural,
=0 {no photos.}
=1 {one photo.}
other {# photos.}
}
var MESSAGES = {
photos: '...', // String from code block above.
...
};
var msg = new IntlMessageFormat(MESSAGES.photos, 'en-US');
console.log(msg.format({numPhotos: 0})); // => "You have no photos."
console.log(msg.format({numPhotos: 1})); // => "You have one photo."
console.log(msg.format({numPhotos: 1000})); // => "You have 1,000 photos."
Note: how when numPhotos
was 1000
, the number is formatted with the correct thousands separator.
format_cached_complex_msg x 539,674 ops/sec ±1.87% (87 runs sampled)
format_cached_string_msg x 99,311,640 ops/sec ±2.15% (87 runs sampled)
new_complex_msg_preparsed x 1,490 ops/sec ±8.37% (54 runs sampled)
new_complex_msg x 836 ops/sec ±31.96% (67 runs sampled)
new_string_msg x 27,752 ops/sec ±8.25% (65 runs sampled)
complex msg format x 799 ops/sec ±9.38% (55 runs sampled)
complex msg w/ formatters format x 1,878 ops/sec ±16.63% (64 runs sampled)
complex preparsed msg w/ formatters format x 26,482 ops/sec ±2.55% (84 runs sampled)
This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.
FAQs
Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
The npm package intl-messageformat receives a total of 0 weekly downloads. As such, intl-messageformat popularity was classified as not popular.
We found that intl-messageformat demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.